<template>
  <div class="container">
    <el-button type="primary" @click="changedata">改变数据</el-button>
    <el-button type="primary" @click="changestyle">改变样式</el-button>
    <el-button type="primary" @click="daochu">导出</el-button>
    <el-button type="primary" @click="daochu2">导出2</el-button>
    <el-button type="primary" @click="daochu3">导出3</el-button>
    <el-button type="primary" @click="daochu4">导出4</el-button>
    <div class="echartsDiv">
      <echartsmy :styleWH="styleWH" :idEcharts="idEcharts" :chartOption="chartOption" :dataSource="dataSource">
      </echartsmy>
    </div>

  </div>
</template>

<script>
import echartsmy from './components/echarts.vue';
import * as XLSX from 'xlsx';
import * as XLSXD from 'xlsx-style-vite'

import { downLoadExcel } from './js/excel'
import { jsonToExcel } from './js/excel2'
import { sheet_from_array_of_arrays } from './js/Export2ExcelStyle'

export default {
  components: {
    echartsmy
  },
  created() {
    // 时间戳+随机字符
    this.idEcharts = 'top' + new Date().getTime() + Math.random().toString(32).slice(2, 10)


  },
  data() {
    return {
      styleWH: {
        width: '100%',
        height: '100%'
      },
      idEcharts: '',
      dataSource: {},
      chartOption: {
        title: {
          text: '南丁格尔玫瑰图',
          x: 'center'
        },
        color: ['#37a2da', '#32c5e9', '#9fe6b8', '#ffdb5c', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378ea'],
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        calculable: true,
        series: [{
          name: '销量',
          type: 'pie',
          radius: ['20%', '50%'],
          roseType: 'area',
          data: []
        }]
      },
      msgList: [
        { name: '1111111', age: 19, sex: '男' },
        { name: '33333', age: 19, sex: '男' },
        { name: '3333334', age: 19, sex: '男' },
      ]
    }
  },
  mounted() {

    // this.$router.go(0)
  },
  methods: {
    changedata() {
      this.dataSource = {
        series: [
          {
            // 根据名字对应到相应的系列
            name: '销量',
            data: [
              { value: 10, name: 'rose1' },
              { value: 5, name: 'rose2' },
              { value: 15, name: 'rose3' },
              { value: 25, name: 'rose4' },
              { value: 20, name: 'rose5' },
              { value: 35, name: 'rose6' },
              { value: 30, name: 'rose7' },
              { value: 40, name: 'rose8' }
            ]
          }
        ]
      }
    },
    changestyle() {
      this.chartOption.title.text = '11111111111'
      console.log('changestyle', this.chartOption);
    },
    daochu() {
      let wb = XLSX.utils.book_new()
      let headers = { name: '姓名', age: '年龄', sex: '性别' }
      this.msgList.unshift(headers)
      let contentWs = XLSX.utils.json_to_sheet(this.msgList, {
        header: ['name', 'age', "sex"],
        skipHeader: true,
      })
      contentWs['A3'].s = {
        font: {
          name: '宋体',
          bold: true,
          sz: 14,
          color: { rgb: 'FFFFAA00' }
        },
        // fill: { bgcolor: { rgb: "FFFFAA00" } },
        fill: {
          fgColor: { rgb: "4472C4" },
        },
      }
      contentWs["!merges"] = [{ s: { r: 0, c: 0 }, e: { r: 0, c: 2 } }]
      contentWs["!cols"] = [{ wch: 50 }, { wch: 20 }, { wch: 50 }]
      XLSX.utils.book_append_sheet(wb, contentWs, '人员明细表')
      const tmpDown = new Blob([
        this.s2ab(
          XLSXD.write(
            wb,
            {
              bookType: 'xlsx',
              bookSST: false,
              type: 'binary',
              cellStyles: true
            }
          )
        )
      ])
      this.downExcel(tmpDown, '人员表.xlsx')
      // XLSX.writeFile(wb, '人员表.xlsx')
      console.log('contentWs', contentWs);
    },
    //自定义下载文件方法
    downExcel(obj, fileName) {
      const a_node = document.createElement("a");
      a_node.download = fileName;
      if ("msSaveOrOpenBlob" in navigator) {
        window.navigator.msSaveOrOpenBlob(obj, fileName);
      } else {
        a_node.href = URL.createObjectURL(obj);
      }
      a_node.click();
      // 11
      setTimeout(() => {
        URL.revoke0bjectURL(obj);
      }, 2000);
    },
    // 文件流转换
    s2ab(s) {
      if (typeof ArrayBuffer !== "undefined") {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i != s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xff;
        }
        return buf;
      } else {
        const buf = new Array(s.length);
        for (let i = 0; i != s.length; ++i) {
          buf[i] = s.charCodeAt(i) & 0xff;

        }
        return buf;
      }
    },
    daochu2() {
      let config = {}

      console.log(11111111111);
      // let exportHead = ["题名", "档号", "全宗号", "分类号", "档案类型", "归档年度", "保管期限"]
      let data = [
        ["题1", "题1-SZZGS-102", "SZZGS", "001", "科技档案（项目）", "2020", "定期10年"],
        ["题2", "题1-SZZGS-103", "SZZGS", "001", "科技档案（项目）", "2020", "定期10年"],
        ["题3", "题1-SZZGS-104", "SZZGS", "001", "科技档案（项目）", "2020", "定期10年"],
      ]
      // import('@/vendor/Export2Excel').then((excel) => {
      //   excel.export_json_to_excel({
      //     header: this.exportHead, // 表头 必填
      //     data: this.exportData, // 具体数据 必填
      //     filename, // 非必填  导出文件名
      //     autoWidth: true, // 非必填   单元格是否要自适应宽度
      //     bookType: 'xlsx' // 非必填   导出文件类型
      //   })
      // })



      // let data = [['xingming', 'age'], ['xxx', 16], ['yyy', 18]]
      downLoadExcel(data, '导出表格', config, [], '导出表格')
    },
    daochu3() {
      const rows = [{ xxx: '' }, { 'yyy': '' }, { 'ccc': '' }]

      jsonToExcel({
        rows,
        name: '模版',
      })
      // 链接：https://juejin.cn/post/7327836344037785652

    },
    daochu4() {
      let multiHeader = [['状态', '编码', '描述', '日数据', '', '', '周数据', '', '']]// 这是一个二维数组(重点!)
      // multiHeader说明: 因为日数据占3格，所以后面需要跟上2个空子元素，这样算上”日数据”就是3格了。同理，周数据也是这样。
      let header = ['', '', '', 'day1', 'day2', 'day3', 'week1', 'week2', 'week3']
      // header 说明: 二级表头这里我们想象成一整行，前面三格被一级表头占领了，所以我们在数组里面前三个子元素为空
      let filterVal = ['status', 'code', 'decs', 'day1', 'day2', 'day3', 'week1', 'week2', 'week3']
      // filterVal说明: 数组里面要包含表头中每一个单元格，当遇到多级表头，应选用最底部的那一级。filterVal内部元素的顺序要和 excel 中显示的一样，否则excel表头和对应的下面这个list 内容是错乱的(重点!)
      let list = [
        { status: '开心', code: "123", decs: '测试', day1: 100, day2: 200, day3: 300, week1: 500, week2: 1000, week3: 810 },
        { status: '开心', code: "123", decs: '要求', day1: 100, day2: 200, day3: 300, week1: 500, week2: 1000, week3: 810 },
        { status: '开心', code: "123", decs: '恢复', day1: 100, day2: 200, day3: 300, week1: 500, week2: 1000, week3: 810 },
        { status: '开心', code: "123", decs: '剩余', day1: 100, day2: 200, day3: 300, week1: 500, week2: 1000, week3: 810 }
      ]
      // list 说明: 一个数组对象，就是表格的每一条内容。
      let merges = ["A1:A2", "B1:B2", "C1:C2", "D1:F1", "G1:I1", "A3:A6", "B3:B6"]//对着下面的截图更好理解merges 说明:看到下面的单元格索引了吗?整个数组就是由这些素引组成
      // 只传入需要合并的单元格索引，单个的那种单元格就不需要传进去了
      // 遵循一个原则: 从左往右，从上到下依次传入就行。顺序没花时间测试，大家有兴趣自己可以测一下会不会乱套.
      const data = this.formatJson(filterVal, list) //这个不管...调方法传参就行

      import("./js/Export2ExcelStyle").then((excel) => {

        // 单元格样式
        const cellStyle = {
          // font: { color: { rgb: 'ff0000' } },
          fill: { fgColor: { rgb: 'ffffcc' } }//设置标题单元格的背景颜色
        }
        // 特殊单元格与样式对应数组
        // specialCell数组：1.虽然'状态'这里，它占A1和A2两格，但只需要传其中一格就行了，同理，'编码'这一格也是传B1就行了
        let specialCell = [
          { type: "A1", s: cellStyle },
          { type: "B1", s: cellStyle },
          { type: "C1", s: cellStyle },
          { type: "D1", s: cellStyle },
          { type: "E1", s: cellStyle },
          { type: "F1", s: cellStyle },
          { type: "G1", s: cellStyle },
          { type: "H1", s: cellStyle },
          { type: "I1", s: cellStyle },
          { type: "A3", s: cellStyle },
          { type: "B3", s: cellStyle }
        ]

        excel.exportStyleExcel({
          multiHeader,
          header,
          data,
          filename: "交货计划表",
          specialCell,
          merges
        });
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j]
        })
      )
    }

  }
}
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  padding: 20px;

  .echartsDiv {
    width: 30%;
    height: 40%;
    background-color: antiquewhite;
  }
}
</style>
